package com.hnblc.blcwms.rest.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hnblc.blcwms.common.constant.StringPool;
import com.hnblc.blcwms.common.exceptions.ErrorDescription;
import com.hnblc.blcwms.common.exceptions.GeneralException;
import com.hnblc.blcwms.common.interaction.Response;
import com.hnblc.blcwms.common.interaction.RestResponse;
import com.hnblc.blcwms.common.utils.encrypt.BASE64;
import com.hnblc.blcwms.persistent.interfaces.business.entity.ExpLog;
import com.hnblc.blcwms.persistent.interfaces.business.service.IExpLogService;
import com.hnblc.blcwms.persistent.interfaces.client.dto.CurrentClient;
import com.hnblc.blcwms.persistent.interfaces.client.entity.ClientAuth;
import com.hnblc.blcwms.persistent.interfaces.message.entity.MessageLog;
import com.hnblc.blcwms.rest.dto.restInteraction.EncryptRequest;
import com.hnblc.blcwms.rest.service.IMessageService;
import com.hnblc.blcwms.serviceapi.api.dto.WareHouseOperate;
import com.hnblc.blcwms.serviceapi.api.dto.purchase.PurchaseHead;
import com.hnblc.blcwms.serviceapi.api.dto.ret.note.RetreatNoteBody;
import com.hnblc.blcwms.serviceapi.api.dto.ret.note.RetreatNoteHead;
import com.hnblc.blcwms.serviceapi.api.enums.code.ExpLogTypeEnum;
import com.hnblc.blcwms.serviceapi.api.group.custom.express.UntreadGroup;
import com.hnblc.blcwms.serviceapi.api.group.owner.purchase.PurchaseGroup;
import com.hnblc.blcwms.serviceapi.api.service.IRetreatNoteAPIService;
import io.swagger.annotations.Api;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * <p>Description: </p> <br/>
 *
 * @author linsong <br>
 * @version 1.0 2020.01.20 14:41 <br>
 */


@Slf4j
@Setter
@Getter
@RestController
@RequestMapping("blc/wms/api/purchase")
@Api(value="采购退货API",description = "采购退货单相关操作",tags={"入库单操作接口"})
@Validated
public class PurchaseRetRestAPI extends BaseRestAPI{



    @Autowired
    IExpLogService expLogService;
    @Autowired
    IMessageService messageService;
    @Autowired
    IRetreatNoteAPIService retreatNoteAPIService;

    @RequestMapping("/create_ret_note")
    @ResponseBody
    public RestResponse createRetNote(@Validated({UntreadGroup.class})@RequestBody EncryptRequest message, HttpServletRequest request) throws IOException {
//测试打印原始报文
        String jsonString = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
        log.debug("***********************************create Purchase test start***************************\n"+jsonString+"\n*********************end*************************");

        //解析业务数据 从BASE64字符串解析为JSON字符串，再解析为业务对象
        WareHouseOperate<RetreatNoteHead> businessData;
        try {
            businessData = objectMapper.readValue(new String(BASE64.decryptBASE64(message.getBusinessData()), StringPool.CHARSET_UTF8),new TypeReference<WareHouseOperate<PurchaseHead>>() { });
        }catch (Exception e){
            e.printStackTrace();
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0,e));
        }

        //简单验证
        this.validate(businessData, PurchaseGroup.class);

        //校验操作权限
        ClientAuth clientAuth = this.buildAuth(message,businessData);
        //货主权限，客户专用位
        clientAuth.setCustomNo("N");
        CurrentClient currentClient = this.clientInfoService.loadCurrentClient(clientAuth);
        if (null == currentClient || currentClient.getClientAuthInfo().size() < 1) {
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_CLIENT_UNAUTHORIZED_0));
        }

        //验签
        try {
            if (!this.signatureValidate(message, currentClient)) {
                return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_SIGNATURE_VALIDATE_FAIL_0));
            }
        } catch (Exception e) {
            log.error("接口处理验签异常", e);
            throw new GeneralException(e);
        }
        MessageLog messageLog = messageService.process(currentClient, request);

        //创建采购单
        Response<List<RetreatNoteBody>> result= retreatNoteAPIService.createRetNote(businessData.getOperateDetails(),currentClient.getClientAuthInfo().get(0));
        //保存创建日志，如果没有则无法反馈操作状态
        ExpLog expLog = new ExpLog(ExpLogTypeEnum.RETREAD.code(),message.getClientId(),messageLog.getSeqNo(),businessData.getOperateDetails().getRetreatNo(),result);
        if(!expLogService.save(expLog)){
            log.error("Error occurred when save [RETREAD NOTE] creation log to database");
        }
        messageService.processed(messageLog);
        return new RestResponse(result);
    }
}
